package com.cxc.mp.simple.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

@Component
public class OracleDbUtil {

    private static final Logger LOGGER = Logger.getLogger(OracleJDBCUtil.class.getName());

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    // Spring Boot会自动注入DataSource，无需使用DriverManager
    @Autowired
    private DataSource dataSource;

    public OracleDbUtil(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getConnection() throws SQLException {
        // 使用Spring Boot管理的DataSource获取连接
        return dataSource.getConnection();
    }

    public void closeConnection(Connection connection) {
        // 通常情况下，Spring Boot会自动管理连接的关闭
        // 但如果您在某些情况下需要手动关闭连接，可以调用connection.close()
        try {
            if (connection != null && !connection.isClosed()) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    LOGGER.log(Level.WARNING, "关闭数据库连接时发生错误", e);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
